import React, { useState } from "react";
import { Modal, Form, Upload, Button, Space, Typography, message, Alert, Divider } from "antd";
import {
  UploadOutlined,
  FileTextOutlined,
  ClockCircleOutlined,
  ExclamationCircleOutlined,
  DeleteOutlined,
} from "@ant-design/icons";
import type { UploadFile, UploadProps } from "antd/es/upload/interface";

const { Text, Title } = Typography;

interface Homework {
  id: string;
  title: string;
  course: string;
  teacher: string;
  description: string;
  deadline: string;
  status: "未提交" | "已提交" | "已批改" | "已过期";
  score?: number;
  fullScore?: number;
  submittedAt?: string;
  gradedAt?: string;
  feedback?: string;
  attachments?: string[];
  submittedFiles?: string[];
}

interface HomeworkSubmissionModalProps {
  visible: boolean;
  homework: Homework | null;
  onClose: () => void;
  onSuccess: () => void;
}

const HomeworkSubmissionModal: React.FC<HomeworkSubmissionModalProps> = ({
  visible,
  homework,
  onClose,
  onSuccess,
}) => {
  const [form] = Form.useForm();
  const [fileList, setFileList] = useState<UploadFile[]>([]);
  const [submitting, setSubmitting] = useState(false);

  // 文件上传配置
  const uploadProps: UploadProps = {
    onRemove: (file) => {
      const index = fileList.indexOf(file);
      const newFileList = fileList.slice();
      newFileList.splice(index, 1);
      setFileList(newFileList);
    },
    beforeUpload: (file) => {
      // 检查文件大小（限制为50MB）
      const isLt50M = file.size / 1024 / 1024 < 50;
      if (!isLt50M) {
        message.error('文件大小不能超过50MB!');
        return false;
      }

      // 检查文件类型
      const allowedTypes = [
        'application/pdf',
        'application/msword',
        'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        'text/plain',
        'text/c',
        'text/cpp',
        'text/java',
        'text/python',
        'application/zip',
        'application/x-rar-compressed',
        'image/jpeg',
        'image/png',
        'image/gif'
      ];
      
      if (!allowedTypes.includes(file.type)) {
        message.error('不支持的文件类型! 请上传PDF、Word、代码文件、压缩包或图片文件。');
        return false;
      }

      setFileList(prev => [...prev, file]);
      return false; // 阻止自动上传
    },
    fileList,
    multiple: true,
  };

  // 提交作业
  const handleSubmit = async () => {
    if (fileList.length === 0) {
      message.error('请至少上传一个文件');
      return;
    }

    setSubmitting(true);
    try {
      // 模拟提交过程
      await new Promise(resolve => setTimeout(resolve, 2000));
      
      message.success('作业提交成功！');
      onSuccess();
    } catch (error) {
      message.error('作业提交失败，请重试');
    } finally {
      setSubmitting(false);
    }
  };

  // 清空文件列表
  const handleClearFiles = () => {
    setFileList([]);
    message.info('已清空文件列表');
  };

  // 检查是否过期
  const isExpired = () => {
    if (!homework) return false;
    const now = new Date();
    const deadline = new Date(homework.deadline);
    return now > deadline;
  };

  if (!homework) {
    return null;
  }

  return (
    <Modal
      title={
        <Space>
          <UploadOutlined />
          提交作业
        </Space>
      }
      open={visible}
      onCancel={onClose}
      footer={[
        <Button key="cancel" onClick={onClose}>
          取消
        </Button>,
        <Button 
          key="clear" 
          onClick={handleClearFiles}
          disabled={fileList.length === 0}
        >
          清空文件
        </Button>,
        <Button 
          key="submit" 
          type="primary" 
          loading={submitting}
          onClick={handleSubmit}
          disabled={fileList.length === 0 || isExpired()}
        >
          提交作业
        </Button>,
      ]}
      width={700}
      destroyOnClose
    >
      <div style={{ marginBottom: 16 }}>
        <Title level={4}>{homework.title}</Title>
        <Space direction="vertical" style={{ width: "100%" }}>
          <div>
            <Text strong>课程：</Text>
            <Text>{homework.course}</Text>
          </div>
          <div>
            <Text strong>教师：</Text>
            <Text>{homework.teacher}</Text>
          </div>
          <div>
            <Text strong>截止时间：</Text>
            <Text type={isExpired() ? "danger" : "secondary"}>
              {homework.deadline}
            </Text>
          </div>
        </Space>
      </div>

      {isExpired() && (
        <Alert
          message="作业已过期"
          description="该作业的提交截止时间已过，无法提交。"
          type="error"
          showIcon
          style={{ marginBottom: 16 }}
        />
      )}

      <Divider />

      <div style={{ marginBottom: 16 }}>
        <Text strong>作业要求：</Text>
        <div style={{ 
          background: "#f6f8fa", 
          padding: "12px", 
          borderRadius: "6px", 
          marginTop: "8px",
          maxHeight: "150px",
          overflowY: "auto"
        }}>
          <Text style={{ whiteSpace: "pre-line" }}>
            {homework.description}
          </Text>
        </div>
      </div>

      {homework.attachments && homework.attachments.length > 0 && (
        <div style={{ marginBottom: 16 }}>
          <Text strong>附件：</Text>
          <div style={{ marginTop: "8px" }}>
            {homework.attachments.map((file, index) => (
              <Text key={index} code style={{ marginRight: "8px" }}>
                {file}
              </Text>
            ))}
          </div>
        </div>
      )}

      <Divider />

      <Form form={form} layout="vertical">
        <Form.Item
          label="上传作业文件"
          required
          help="支持PDF、Word、代码文件、压缩包、图片等格式，单个文件不超过50MB"
        >
          <Upload {...uploadProps}>
            <Button icon={<UploadOutlined />} disabled={isExpired()}>
              选择文件
            </Button>
          </Upload>
        </Form.Item>

        {fileList.length > 0 && (
          <div style={{ marginTop: 16 }}>
            <Text strong>已选择的文件 ({fileList.length}个)：</Text>
            <div style={{ 
              background: "#f9f9f9", 
              padding: "12px", 
              borderRadius: "6px", 
              marginTop: "8px",
              maxHeight: "200px",
              overflowY: "auto"
            }}>
              {fileList.map((file, index) => (
                <div key={index} style={{ 
                  display: "flex", 
                  justifyContent: "space-between", 
                  alignItems: "center",
                  padding: "4px 0",
                  borderBottom: index < fileList.length - 1 ? "1px solid #eee" : "none"
                }}>
                  <Space>
                    <FileTextOutlined />
                    <Text>{file.name}</Text>
                    <Text type="secondary">({(file.size! / 1024 / 1024).toFixed(2)}MB)</Text>
                  </Space>
                  <Button
                    type="text"
                    size="small"
                    icon={<DeleteOutlined />}
                    onClick={() => {
                      const newFileList = fileList.filter((_, i) => i !== index);
                      setFileList(newFileList);
                    }}
                  />
                </div>
              ))}
            </div>
          </div>
        )}

        <Alert
          message="提交须知"
          description={
            <ul style={{ margin: 0, paddingLeft: "20px" }}>
              <li>请确保上传的文件格式正确，内容完整</li>
              <li>提交后无法修改，请仔细检查后再提交</li>
              <li>建议在截止时间前提前提交，避免网络问题</li>
              <li>如有问题，请及时联系任课教师</li>
            </ul>
          }
          type="info"
          showIcon
          style={{ marginTop: 16 }}
        />
      </Form>
    </Modal>
  );
};

export default HomeworkSubmissionModal; 